package com.homework.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.homework.dto.MistakeQuestionDTO;
import com.homework.dto.MistakeSubjectDTO;
import com.homework.entity.MistakeQuestion;
import com.homework.entity.MistakeSubject;
import com.homework.mapper.MistakeQuestionMapper;
import com.homework.mapper.MistakeSubjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class MistakeService {

    private final MistakeSubjectMapper mistakeSubjectMapper;
    private final MistakeQuestionMapper mistakeQuestionMapper;

    /**
     * 获取所有科目
     */
    public List<MistakeSubject> getAllSubjects() {
        try {
            LambdaQueryWrapper<MistakeSubject> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByAsc(MistakeSubject::getName);
            return mistakeSubjectMapper.selectList(wrapper);
        } catch (Exception e) {
            log.error("获取科目列表失败", e);
            throw new RuntimeException("获取科目列表失败: " + e.getMessage());
        }
    }

    /**
     * 创建科目
     */
    @Transactional
    public MistakeSubject createSubject(MistakeSubjectDTO dto) {
        try {
            // 检查科目名称是否已存在
            LambdaQueryWrapper<MistakeSubject> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.eq(MistakeSubject::getName, dto.getName());
            MistakeSubject existing = mistakeSubjectMapper.selectOne(checkWrapper);
            if (existing != null) {
                throw new RuntimeException("科目名称已存在");
            }

            MistakeSubject subject = new MistakeSubject();
            subject.setName(dto.getName());

            mistakeSubjectMapper.insert(subject);
            log.info("创建科目成功: {}", subject.getName());
            return subject;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("创建科目失败", e);
            throw new RuntimeException("创建科目失败: " + e.getMessage());
        }
    }

    /**
     * 获取错题列表（带分页和搜索）
     */
    public Page<MistakeQuestion> getQuestions(Long subjectId, String keyword, Integer page, Integer size) {
        try {
            Page<MistakeQuestion> pageParam = new Page<>(page != null ? page : 1, size != null ? size : 10);
            LambdaQueryWrapper<MistakeQuestion> wrapper = new LambdaQueryWrapper<>();

            if (subjectId != null) {
                wrapper.eq(MistakeQuestion::getSubjectId, subjectId);
            }

            if (StringUtils.hasText(keyword)) {
                wrapper.and(w -> w.like(MistakeQuestion::getTitle, keyword)
                                        .or()
                                        .like(MistakeQuestion::getContent, keyword));
            }

            wrapper.orderByDesc(MistakeQuestion::getCreatedAt);

            return mistakeQuestionMapper.selectPage(pageParam, wrapper);
        } catch (Exception e) {
            log.error("获取错题列表失败", e);
            throw new RuntimeException("获取错题列表失败: " + e.getMessage());
        }
    }

    /**
     * 创建错题
     */
    @Transactional
    public MistakeQuestion createQuestion(MistakeQuestionDTO dto) {
        try {
            // 验证科目是否存在
            MistakeSubject subject = mistakeSubjectMapper.selectById(dto.getSubjectId());
            if (subject == null) {
                throw new RuntimeException("科目不存在");
            }

            MistakeQuestion question = new MistakeQuestion();
            question.setSubjectId(dto.getSubjectId());
            question.setTitle(dto.getTitle());
            question.setContent(dto.getContent());
            question.setImageUrl(dto.getImageUrl());

            mistakeQuestionMapper.insert(question);
            log.info("创建错题成功: 科目={}, 标题={}", subject.getName(), dto.getTitle());
            return question;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("创建错题失败", e);
            throw new RuntimeException("创建错题失败: " + e.getMessage());
        }
    }

    /**
     * 删除错题
     */
    @Transactional
    public void deleteQuestion(Long questionId) {
        try {
            MistakeQuestion question = mistakeQuestionMapper.selectById(questionId);
            if (question == null) {
                throw new RuntimeException("错题不存在");
            }

            mistakeQuestionMapper.deleteById(questionId);
            log.info("删除错题成功: ID={}", questionId);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("删除错题失败", e);
            throw new RuntimeException("删除错题失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个错题详情
     */
    public MistakeQuestion getQuestionById(Long questionId) {
        try {
            MistakeQuestion question = mistakeQuestionMapper.selectById(questionId);
            if (question == null) {
                throw new RuntimeException("错题不存在");
            }
            return question;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取错题详情失败", e);
            throw new RuntimeException("获取错题详情失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取科目信息
     */
    public MistakeSubject getSubjectById(Long subjectId) {
        try {
            MistakeSubject subject = mistakeSubjectMapper.selectById(subjectId);
            return subject;
        } catch (Exception e) {
            log.error("获取科目信息失败", e);
            return null;
        }
    }
}